import React, { useEffect } from 'react';
import { Form, Input, Select, Button } from 'antd'
import { fieldType } from '../setting'

import '../index.less'

export default function NewField(props: any) {
  const [form] = Form.useForm();

  const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };

  const tailLayout = {
    wrapperCol: { offset: 8, span: 16 },
  };

  function onFinish(values: any) {
    const { onSave } = props;
    onSave(values);
  }

  return (
    <div style={{ margin: "0 auto", textAlign: 'center' }}>
      <Form
        {...layout}
        name="basic"
        initialValues={{ remember: true }}
        onFinish={onFinish}
        style={{ textAlign: 'left' }}
        form={form}
      >
        <Form.Item
          label="类型"
          name="type"
          rules={[{ required: true, message: '请选择' }]}
        >
          <Select>
            {Object.keys(fieldType).map((key: string) => {
              return <Select.Option value={key} key={key}>{fieldType[key].text}</Select.Option>
            })}
          </Select>
        </Form.Item>
        <Form.Item
          label="字段名"
          name="name"
          rules={[{ required: true, message: '请输入' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item shouldUpdate noStyle>
          {
            () => {
              console.log(fieldType[form.getFieldValue("type")]);
              const type = form.getFieldValue("type");
              if (!type || !fieldType[type] || !fieldType[type].settings) return null;
              return fieldType[type].settings.map((item: any) => (
                <Form.Item
                  label={item.label}
                  name={["setting", item.key]}
                >
                  <Input />
                </Form.Item>
              ))
            }
          }
        </Form.Item>
        <Form.Item {...tailLayout}>
          <Button type="primary" size="large" htmlType="submit" block>
            保存
        </Button>
        </Form.Item>
      </Form>
    </div>
  );
}
